*===================================================================================*
* Ado-file: 	csxmpcadr Version 1.0 
* Author: 		Chen Shao(陈志豪)
* Affiliation: 	Lanzhou University
* E-mail: 		chenzhh20@lzu.edu.cn
* License:      Mulan PSL v2
* Date: 		2025/2/17                                 
*===================================================================================*

capture program drop csxmpcadr
program define csxmpcadr
	version 16
	syntax varlist(min=2) [if] [in] ,Genvar(string)
	di in blue "晨韶学妹向您报告："
	local xs "`varlist'"
	local x "`genvar'"
	local cunzhao=1
	while `cunzhao'==1{
		qui pca `xs'
		qui estat kmo
		local kmo=r(kmo)
		while `kmo'>=0{
			local result "不能接受"
			while `kmo'>=0.5{
				local result "非常差"
				while `kmo'>=0.6{
					local result "勉强接受"
					while `kmo'>=0.7{
						local result "可以接受"
						while `kmo'>=0.8{
							local result "比较好"
							while `kmo'>=0.9{
								local result "非常好"
								local kmo=-1
							}
							local kmo=-1
						}
						local kmo=-1
					}
					local kmo=-1
				}
				local kmo=-1
			}
			local kmo=-1
		}
		di in white "首先，KMO检验认为变量的共性`result'。"
		qui pca `xs'
		mat Ev=e(Ev)
		local f=e(f) 
		local lag=1
		local cumulative =0
		while `cumulative' <= 0.85{
			local cumulative =`cumulative'+ el(Ev,1,`lag')/`f'
			local lag=`lag'+1
			local comp=el(Ev,1,`lag')
		}
		if `lag'<=`f'{
		    while `comp'>1{
				local cumulative =`cumulative'+ el(Ev,1,`lag')/`f'
				local lag=`lag'+1
				local comp=el(Ev,1,`lag')
			}
		}
		g `x'=0
		local i=1
		while `i'<`lag'{
			qui predict c`i'
			qui replace `x'=`x'+c`i'*el(Ev,1,`lag')/`f'
			drop c`i'
			local i=`i'+1
		}
		qui replace `x'=`x'/`cumulative'
		local lag=`lag'-1
		di in white "其次，自动选择的主成分数量为`lag'，"
		di in white "此时，累积方差解释率为`cumulative'。"
		di in white "最终，降维后得到的变量为`x'。"
		di in blue "您布置的任务已经完成，请您过目~♥"
		local cunzhao=0
	}
end